package cn.wk.libs4a.view;

import java.io.File;

import uk.co.senab.photoview.PhotoViewAttacher;
import uk.co.senab.photoview.PhotoViewAttacher.OnPhotoTapListener;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import cn.wk.libs4a.R;
import cn.wk.libs4a.WKBaseActivity;

import com.itotem.imageloader.core.assist.FailReason;
import com.itotem.imageloader.core.assist.ImageLoadingListener;

/**
 * 全屏看大图的方法
 * 
 * Intent i = new Intent(mContext, WKPhotoView.class);
 * 
 * i.putExtra("img", "" +url);
 * 
 * mContext.startActivity(i);
 */
public class WKPhotoView extends WKBaseActivity {

	private ImageView iv_photo;
	private PhotoViewAttacher mAttacher;
	private String imgUrl;

	public Handler bitmapUrlLoad = new Handler(new Callback() {
		public boolean handleMessage(Message msg) {
			return false;
		}
	});

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (mAttacher != null)
			mAttacher.cleanup();
		app().recycleImageView(iv_photo);
	}

	@Override
	public void loadXml() {
		setContentView(R.layout.wk_photo_view);
	}

	@Override
	public void init() {
		iv_photo = (ImageView) findViewById(R.id.iv_photo);
		iv_photo.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
	}

	@Override
	public void setData() {
		Bundle bundle = getIntent().getExtras();
		if (bundle == null)
			return;
		imgUrl = bundle.getString("img");
		if (imgUrl == null || imgUrl.equals("")) {
			return;
		}
		if (imgUrl.contains("http")) {
			app().imageLoader.displayImage(imgUrl, iv_photo,
					new ImageLoadingListener() {
						public void onLoadingStarted() {
						}

						public void onLoadingFailed(FailReason arg0) {
							addBackMethon();
						}

						public void onLoadingComplete(Bitmap arg0) {
							addBackMethon();
						}

						public void onLoadingCancelled() {
						}
					});
		} else {
			iv_photo.setImageURI(Uri.fromFile(new File(imgUrl)));
		}

	}

	private void addBackMethon() {
		mAttacher = new PhotoViewAttacher(iv_photo);
		mAttacher.setOnPhotoTapListener(new OnPhotoTapListener() {
			public void onPhotoTap(View arg0, float arg1, float arg2) {
				finish();
			}
		});
	}
}
